import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { EnvSwaggerOptions } from './config/env/swagger.config';
import { EnvDatabaseOptions } from './config/env/database.config';
import { terminalHelpTextConsole } from './utils/terminal-help-text-console';
import { TransformInterceptor } from './interceptor/transform.interceptor';
import { HttpExceptionFilter } from './filter/http-exception.filter';
import { AnyExceptionFilter } from './filter/any-exception.filter';
// import DB_MySQL from './database/sequelize';
// import { LoggerMiddleware } from './middleware/logger.middleware';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: false,
    logger: false,
  });

  const configService = app.get(ConfigService);
  // swagger option setting
  const swaggerOpts = configService.get<EnvSwaggerOptions>('EnvSwaggerOptions');
  const options = new DocumentBuilder()
    .setTitle(swaggerOpts.title)
    .setDescription(swaggerOpts.desc)
    .setVersion(swaggerOpts.version)
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup(swaggerOpts.setupUrl, app, document, {
    customSiteTitle: swaggerOpts.title,
    swaggerOptions: {
      docExpansion: 'list',
      filter: true,
      showRequestDuration: true,
    },
  });
  // mysql option
  // const dbOpts = configService.get<EnvDatabaseOptions>('EnvDatabaseOptions');
  // const db = new DB_MySQL(dbOpts);
  // db.test();
  // app.use(LoggerMiddleware);
  app.setGlobalPrefix(configService.get('SWAGGER_ENDPOINT_PREFIX'));
  app.useGlobalInterceptors(new TransformInterceptor());
  // anyException 要在 httpException 前面，应该是遵循的 中间件的洋葱模型 ，还有疑问
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalFilters(new AnyExceptionFilter());
  await app.listen(configService.get('SERVE_LISTENER_PORT'));
}
bootstrap().then(() => {
  terminalHelpTextConsole();
  console.log(process.env.NODE_ENV);
});
